﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using MongoDB.Driver.Linq;

namespace DatabaseRepository
{
    public class UserRepository : IUserRepository
    {
        private readonly MongoConnectionHelper<Users> _users;

        public UserRepository() {
            _users = new MongoConnectionHelper<Users>();
        }

        public bool CreateUser(string username, string password) {
            try
            {
                _users.Collection.Save(new Users {Username = username, Password = password});
                return true;
            }
            catch (Exception) {
                return false;
            }
        }

        public string[] GetRoles(string username)
        {
            try
            {
                return (from u in _users.Collection.AsQueryable()
                        where u.Username.Equals(username)
                        select u.Role).SingleOrDefault() ?? new string[0]; 
            }
            catch (Exception)
            {
                return new string[0];
            }
        }

        public bool ValidateUser(string username, string password)
        {
            try
            {
                return (from u in _users.Collection.AsQueryable()
                        where u.Username.Equals(username) && u.Password.Equals(password)
                        select u).Any();
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
